//
//  HomeListViewController.m
//  YiKao2
//
//  Created by Mac Jc on 15/7/29.
//  Copyright (c) 2015年 Mac Jc. All rights reserved.
//

#import "HomeListViewController.h"
#import "TMQuiltView.h"
#import "HomeWaterFlowCell.h"
#import "HomeDetialViewController.h"
#import "AllHeader.h"
#import "GHContextMenuView.h"
#import "HomeListModel.h"


#define kURL @"http://arts1.dlab.com.cn/app/getphotolist"

@interface HomeListViewController ()<TMQuiltViewDataSource,TMQuiltViewDelegate,GHContextOverlayViewDataSource, GHContextOverlayViewDelegate>
{
    TMQuiltView *qtmquitView;
}
//获取数据源
@property (nonatomic ,strong) NSMutableArray *dataSource;

@property (nonatomic, retain) NSMutableArray *images;

@end

@implementation HomeListViewController

@synthesize images = _images;

//懒加载
- (NSMutableArray *)dataSource
{
    if (_dataSource == nil)
    {
        self.dataSource = [NSMutableArray array];
    }
    return _dataSource;
}

- (void)viewDidAppear:(BOOL)animated
{
    [qtmquitView reloadData];
    [self refreshView];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.hidden = YES;
    self.view.backgroundColor = kBackgroundColor;
    
    qtmquitView = [[TMQuiltView alloc] initWithFrame:CGRectMake(0, 20 * HEIGHT, SCREEN_WIDTH, SCREEN_HEIGHT)];
    qtmquitView.delegate = self;
    qtmquitView.dataSource = self;
    
    [self.view addSubview:qtmquitView];
    
    [qtmquitView reloadData];
    [self createHeaderView];
    [self performSelector:@selector(testFinishedLoadData) withObject:nil afterDelay:0.0f];
    
    // 提取当前用户的登陆状态
    NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:@"dataForKeyAndUid"];
    NSInteger loginStatius = [dic[@"status"] integerValue];
    
    // 当提取到的用户登陆状态为1时，不再添加登陆页面，否则添加登陆界面
    if(loginStatius != 1)
    {
        [self createLoginView];
    }
    else
    {
        self.tabBarController.tabBar.hidden = NO;
    }
    
    
    GHContextMenuView* overlay = [[GHContextMenuView alloc] init];
    overlay.dataSource = self;
    overlay.delegate = self;
    
    UILongPressGestureRecognizer* _longPressRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:overlay action:@selector(longPressDetected:)];
    [self.view setUserInteractionEnabled:YES];
    [self.view addGestureRecognizer:_longPressRecognizer];
    
    [self requestData];
    
}

#pragma mark - 请求数据
/**
 *  请求数据
 */
- (void)requestData
{
    AFHTTPRequestOperationManager *manage = [AFHTTPRequestOperationManager manager];
    manage.responseSerializer.acceptableContentTypes = [NSSet setWithObject:@"text/html"];
    manage.responseSerializer = [AFHTTPResponseSerializer serializer];
    
    [manage POST:kURL parameters:nil
         success:^(AFHTTPRequestOperation *operation, id responseObject) {
             NSDictionary * dic = [NSJSONSerialization JSONObjectWithData:responseObject options:(NSJSONReadingMutableContainers) error:nil];
             
             int status = [dic[@"status"] intValue];
             
             if (responseObject)
             {
                 if (status == 1)//状态为1的时候请求成功
                 {
                     NSArray *array = dic[@"list"];
                     
                     for (NSDictionary *dict in array)
                     {
                         HomeListModel *model = [[HomeListModel alloc] init];
                         [model setValuesForKeysWithDictionary:dict];
                         [self.dataSource addObject:model];
                     }
                 }
             }
             [qtmquitView reloadData];
             
             // 请求成功的时候调用这个block
             NSLog(@"数据请求-------------%@", dic);
         } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
             // 请求失败的时候调用调用这个block
             NSLog(@"请求失败");
         }];
}

#pragma mark --长按手势代理

- (NSInteger) numberOfMenuItems
{
    return 3;
}

-(UIImage*) imageForItemAtIndex:(NSInteger)index
{
    NSString* imageName = nil;
    switch (index) {
        case 0:
            imageName = @"facebook-white";
            break;
        case 1:
            imageName = @"twitter-white";
            break;
        case 2:
            imageName = @"google-plus-white";
        default:
            break;
    }
    return [UIImage imageNamed:imageName];
}

- (void) didSelectItemAtIndex:(NSInteger)selectedIndex forMenuAtPoint:(CGPoint)point
{
    NSString* msg = nil;
    switch (selectedIndex) {
        case 0:
            msg = @"Facebook Selected";
            break;
        case 1:
            msg = @"Twitter Selected";
            break;
        case 2:
            msg = @"Google Plus Selected";
            break;
        default:
            break;
    }
    
    UIAlertView* alertView = [[UIAlertView alloc] initWithTitle:nil message:msg delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
    
}

/**
 *  创建登陆页面
 */
- (void)createLoginView
{
    
    LoginBasicViewController *loginBVC = [[LoginBasicViewController alloc] init];
    UINavigationController *navi = [[UINavigationController alloc] initWithRootViewController:loginBVC];
    self.tabBarController.tabBar.hidden = YES;
   
    loginBVC.showbarblock = ^(){
        // 登陆成功后，显示tabbar ，将登陆界面移除，显示主页面
        self.tabBarController.tabBar.hidden = NO;
        [navi.view removeFromSuperview];
    };
    [self.view addSubview:navi.view];
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - 初始化刷新视图
#pragma methods for creating and removing the header view
/**
 *  初始化刷新视图
 */
-(void)createHeaderView
{
    if (_refreshHeaderView && [_refreshHeaderView superview]) {
        [_refreshHeaderView removeFromSuperview];
    }
    _refreshHeaderView = [[EGORefreshTableHeaderView alloc] initWithFrame:CGRectMake(0.0f, 0.0f - self.view.bounds.size.height,self.view.frame.size.width, self.view.bounds.size.height)];
    _refreshHeaderView.delegate = self;
    
    [qtmquitView addSubview:_refreshHeaderView];
    
    [_refreshHeaderView refreshLastUpdatedDate];
}

-(void)testFinishedLoadData{
    
    [self finishReloadingData];
    [self setFooterView];
}

#pragma mark -
#pragma mark method that should be called when the refreshing is finished
- (void)finishReloadingData{
    
    //  model should call this when its done loading
    _reloading = NO;
    
    if (_refreshHeaderView) {
        [_refreshHeaderView egoRefreshScrollViewDataSourceDidFinishedLoading:qtmquitView];
    }
    
    if (_refreshFooterView) {
        [_refreshFooterView egoRefreshScrollViewDataSourceDidFinishedLoading:qtmquitView];
        [self setFooterView];
    }
    
    // overide, the actula reloading tableView operation and reseting position operation is done in the subclass
}

-(void)setFooterView{
    //    UIEdgeInsets test = self.aoView.contentInset;
    // if the footerView is nil, then create it, reset the position of the footer
    CGFloat height = MAX(qtmquitView.contentSize.height, qtmquitView.frame.size.height);
    if (_refreshFooterView && [_refreshFooterView superview])
    {
        // reset position
        _refreshFooterView.frame = CGRectMake(0.0f,height,qtmquitView.frame.size.width,self.view.bounds.size.height);
    }else
    {
        // create the footerView
        _refreshFooterView = [[EGORefreshTableFooterView alloc] initWithFrame:CGRectMake(0.0f, height,qtmquitView.frame.size.width, self.view.bounds.size.height)];
        _refreshFooterView.delegate = self;
        [qtmquitView addSubview:_refreshFooterView];
    }
    
    if (_refreshFooterView)
    {
        [_refreshFooterView refreshLastUpdatedDate];
    }
}


-(void)removeFooterView
{
    if (_refreshFooterView && [_refreshFooterView superview])
    {
        [_refreshFooterView removeFromSuperview];
    }
    _refreshFooterView = nil;
}

//===============
//刷新delegate
#pragma mark -
#pragma mark data reloading methods that must be overide by the subclass

-(void)beginToReloadData:(EGORefreshPos)aRefreshPos{
    
    //  should be calling your tableviews data source model to reload
    _reloading = YES;
    
    if (aRefreshPos == EGORefreshHeader)
    {
        // pull down to refresh data
        [self performSelector:@selector(refreshView) withObject:nil afterDelay:2.0];
    }else if(aRefreshPos == EGORefreshFooter)
    {
        // pull up to load more data
        [self performSelector:@selector(getNextPageView) withObject:nil afterDelay:2.0];
    }
}

//刷新调用的方法
-(void)refreshView
{
    NSLog(@"刷新完成");
    [self testFinishedLoadData];
    
}
//加载调用的方法
-(void)getNextPageView
{
    for(int i = 0; i < 10; i++) {
        [_images addObject:[NSString stringWithFormat:@"%d.jpeg", i % 10 + 1]];
    }
    [qtmquitView reloadData];
    [self removeFooterView];
    [self testFinishedLoadData];
}

#pragma mark -
#pragma mark UIScrollViewDelegate Methods

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    if (_refreshHeaderView)
    {
        [_refreshHeaderView egoRefreshScrollViewDidScroll:scrollView];
    }
    
    if (_refreshFooterView)
    {
        [_refreshFooterView egoRefreshScrollViewDidScroll:scrollView];
    }
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    if (_refreshHeaderView)
    {
        [_refreshHeaderView egoRefreshScrollViewDidEndDragging:scrollView];
    }
    
    if (_refreshFooterView)
    {
        [_refreshFooterView egoRefreshScrollViewDidEndDragging:scrollView];
    }
}


#pragma mark -
#pragma mark EGORefreshTableDelegate Methods

- (void)egoRefreshTableDidTriggerRefresh:(EGORefreshPos)aRefreshPos
{
    
    [self beginToReloadData:aRefreshPos];
    
}

- (BOOL)egoRefreshTableDataSourceIsLoading:(UIView*)view{
    
    return _reloading; // should return if data source model is reloading
    
}


// if we don't realize this method, it won't display the refresh timestamp
- (NSDate*)egoRefreshTableDataSourceLastUpdated:(UIView*)view
{
    
    return [NSDate date]; // should return date data source was last changed
    
}


//- (NSMutableArray *)images
//{
//    if (!_images)
//    {
//        NSMutableArray *imageNames = [NSMutableArray array];
//        for(int i = 0; i < 10; i++) {
//            [imageNames addObject:[NSString stringWithFormat:@"%d.jpeg", i % 10 + 1]];
//        }
//    }
//    return _images;
//}


//- (UIImage *)imageAtIndexPath:(NSIndexPath *)indexPath
//{
//    return [UIImage imageNamed:[self.images objectAtIndex:indexPath.row]];
//}
//
- (NSInteger)quiltViewNumberOfCells:(TMQuiltView *)TMQuiltView {
    return self.dataSource.count;
}

- (TMQuiltViewCell *)quiltView:(TMQuiltView *)quiltView cellAtIndexPath:(NSIndexPath *)indexPath {
    HomeWaterFlowCell *cell = (HomeWaterFlowCell *)[quiltView dequeueReusableCellWithReuseIdentifier:@"PhotoCell"];
    if (cell == nil) {
        cell = [[[HomeWaterFlowCell alloc] initWithReuseIdentifier:@"PhotoCell"] autorelease];
    }
    HomeListModel *model = _dataSource[indexPath.row];
    cell.model = model;
    
    
    
    
//    cell.photoView.image = [self imageAtIndexPath:indexPath];
//    cell.iconView.image = [self imageAtIndexPath:indexPath];
//
//    cell.tagLabel.text = [NSString stringWithFormat:@"素描,色彩,水彩,头像 %ld", (long)indexPath.row];
//    cell.authorLabel.text = [NSString stringWithFormat:@"作者名字"];
//    cell.describeLabel.text = [NSString stringWithFormat:@"特征是留着草绿色波浪长发（动画版则为浅绿色），瞳色为金黄色，左眼不时被浏海遮盖，并有着曼妙身材的美女。。"];
//    
//    cell.viewNumLabel.text = [NSString stringWithFormat:@"%ld", 38 + (long)indexPath.row];
//    cell.CommentNumLabel.text = [NSString stringWithFormat:@"%ld", 765 + (long)indexPath.row];
    
    return cell;
}

#pragma mark - TMQuiltViewDelegate


/**
 *  返回多少个分区
 *
 *  @param quiltView quiltView
 *
 *  @return 分区个数
 */
- (NSInteger)quiltViewNumberOfColumns:(TMQuiltView *)quiltView
{
    if ([[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeLeft
        || [[UIDevice currentDevice] orientation] == UIDeviceOrientationLandscapeRight)
    {
        return 3;
    } else {
        return 2;
    }
}


/**
 *  设置cell的高度
 *
 *  @param quiltView quiltView
 *  @param indexPath indexPath
 *
 *  @return 返回cell的高度
 */
- (CGFloat)quiltView:(TMQuiltView *)quiltView heightForCellAtIndexPath:(NSIndexPath *)indexPath
{
    //  原来的返回图片的方法
//    return [self imageAtIndexPath:indexPath].size.height / [self quiltViewNumberOfColumns:quiltView];
    
//    UIImage *image = [self imageAtIndexPath:indexPath];
//    CGFloat cellHeight = image.size.height / image.size.width * 172.5 * WIDTH;
//    return cellHeight + 104 * HEIGHT;
    return 300;
}


/**
 *  点击cell请入详情页面
 *
 *  @param quiltView 当前视图
 *  @param indexPath indexPath
 */
- (void)quiltView:(TMQuiltView *)quiltView didSelectCellAtIndexPath:(NSIndexPath *)indexPath
{
    NSLog(@"selected index:%ld",(long)indexPath.row);
    
    HomeWaterFlowCell *cell = (HomeWaterFlowCell *)[quiltView cellAtIndexPath:indexPath];
    
    
    HomeDetialViewController *homeDetialVC = [[HomeDetialViewController alloc] init];
    homeDetialVC.backgroundImage = cell.photoView.image;
    homeDetialVC.iconImage = cell.iconView.image;
    homeDetialVC.tagString = cell.tagLabel.text;
    homeDetialVC.authorString = cell.authorLabel.text;
    homeDetialVC.describeString = cell.describeLabel.text;
    homeDetialVC.commentNumString = cell.CommentNumLabel.text;
    homeDetialVC.goodNumString = @"235";
    homeDetialVC.viewNumString = cell.viewNumLabel.text;
    homeDetialVC.hidesBottomBarWhenPushed = YES;
    [self.navigationController pushViewController:homeDetialVC animated:YES];
    homeDetialVC.hidesBottomBarWhenPushed = NO;
}



@end
